<template>
	<view class="shop">
		<!-- #ifdef MP-WEIXIN -->
		<view class="head" :style="{height: pHeight + tHeight + 'px'}">
			<view class="xztitle" :style="[{height: pHeight + 'px', top: tHeight + 'px',lineHeight: pHeight + 'px'}]">
				自助售货
				<view class="iconfont icon-dayuhao1" @click="fanhui"></view>
			</view>
		</view>
		<view class="headtop" :style="{marginTop: pHeight + tHeight + 'px'}">
			<image :src="baseUrl + '/wximage/img/xian_shopbj.png'"></image>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<view class="headtop">
			<image :src="baseUrl + '/wximage/img/xian_shopbj.png'"></image>
		</view>
		<!-- #endif -->

		<view class="content clearfix">
			<view class="list" v-for="(item,index) in deviceInfo1.good" :key="index">
				<image :src="baseUrl + '/wximage/img/xian_shop.png'" class="image"></image>
				<view class="title"><text class="cang" v-if="item.positions == 1">左仓</text><text class="cang"
						v-if="item.positions == 2">右仓</text>{{item.name}}</view>
				<view class="li clearfix">
					<view class="price fl">{{item.danjia}}</view>
					<view class="goumai fr" v-if="item.status==1" @click="orderPrice(item)">立即购买</view>
					<view class="yishou fr" v-else-if="item.status==3" @click="chongxintan(item)">重新出仓</view>
					<view class="yishou fr" v-else>已售罄</view>
				</view>
				<view class="xuhao">{{index+1}}</view>
			</view>
		</view>
		<view class="kefu" @click="call">
			<image :src="baseUrl + '/wximage/img/xian_kefu.png'"></image>
			<view class="desc">客服</view>
		</view>
		<view class="beijing" v-if="hidden == true"></view>
		<view class="tankuang" v-if="hidden == true">
			<image :src="baseUrl + '/wximage/img/xian_weitu.png'" class="tankuangbj"></image>
			<view class="con">
				<view class="title">蓝牙连接失败</view>
				<view class="detail">
					<view class="desc">1.请确认充电器插上电源并且指示灯亮起</view>
					<view class="desc">2.请确认已经打开<text>【蓝牙】</text>和<text>【定位】</text></view>
					<view class="yuxun" @click="dakai">点击打开 ->【微信蓝牙设置】</view>
					<view class="yuxun" @click="yunxu">点击允许 ->【小程序使用蓝牙】</view>
				</view>
				<image :src="baseUrl + '/wximage/img/xian_daotu.png'" class="zhishi"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseUrl: getApp().globalData.baseUrl,
				headerTop: 0,
				pHeight: 0,
				tHeight: 0,
				phone: '',
				hidden: false,
				qrcode: '',
				deviceInfo1: [],
				danhao: '',
				orderInterval: null,
				charger_number: '',
				combo: [],
				deviceInfo: {},
				getBlueIntervalNum: 1,
				getBluetoothIntval: null,
				deviceId: '',
				connectedDeviceId: '', //链接的id
				services: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				characteristics: '',
				notifyServicweId: '',
				writeServicweId: '',
				sendNum: 0,
				type: 1,
				sendProgress_status: false,
				deviceReset: 0,
				orderOk: 0,
				goodType: 1,
				positions: 0,
				charger_pass: '',
				phone: '',
				sucg:0
			}
		},
		onLoad(options) {
			this.qrcode = options.qrcode;
			this.onLocationAuth();
			// 头部距离
			let res = uni.getSystemInfoSync() ///微信api方法
			let titleH;
			if (res && res['system']) {
				// 判断是否是安卓操作系统 （标题栏苹果为44px,安卓为48px）
				if (res['system'].indexOf('Android') > 0) {
					titleH = 48
				} else {
					titleH = 46
				}
				this.headerTop = titleH + res['statusBarHeight']
				this.pHeight = titleH
				this.tHeight = res['statusBarHeight']
			}

			// #ifdef MP-ALIPAY
			my.setNavigationBar({
				frontColor: '#333333',
				backgroundColor: '#cefbfd',
			})
			// 设置导航栏标题
			my.setNavigationBar({
				title: '自助售货'
			})
			// #endif
			//获取设备的信息
			this.deviceInfoFun();

		},

		beforeDestroy() {
			if (this.getBluetoothIntval) {
				clearInterval(this.getBluetoothIntval);
				this.getBluetoothIntval = null;
			}
		},
		methods: {
			//获取设备的信息
			deviceInfoFun() {
				var that = this;
				that.request({
					url: '/wxdevice/boxdeviceinfo',
					data: {
						qrcode: that.qrcode
					}, //充电线
					method: "POST"
				}).then(res => {

					that.deviceInfo1 = res.data.data;
					var charger_pass = res.data.data.charger.charger_pass;
					that.charger_number = res.data.data.charger.charger_number;
					that.phone = res.data.data.station.phone;

					that.passarr(charger_pass);

				});
			},
			chongxintan(item){
				this.positions = item.positions;
				this.goodType = 2;
				// console.log("开始准备执行");
				// this.onLocationAuth();
				//
				console.log("给我弹出了这枚多");
				if(this.connectedDeviceId!=''&&this.writeServicweId!=''&&this.writeCharacteristicsId!=''){
					this.setSendStr();
				}else{
					this.onLocationAuth();	
				}
				
				// deviceId: that.connectedDeviceId,
				// serviceId: that.writeServicweId,
				// characteristicId: that.writeCharacteristicsId,
				
				
				clearInterval(this.orderInterval);
			},
			call(){
				let phone = this.phone;
				
				uni.makePhoneCall({
					phoneNumber: phone,
					success() {
				
					}
				})
			},
			passarr(charger_pass) {
				console.log("打印一下");
				console.log(charger_pass);
				let arr = [];
				arr = [...charger_pass];

				for (let i = 0; i < arr.length; i++) {
					arr[i] = '0' + arr[i];
				}
				this.charger_pass = arr.join("");

				console.log("真正的密码");
				console.log(this.charger_pass);
			},

			//查询订单是否支付
			orderInfo(danhao) {
				var that = this;
				that.orderInterval = setInterval(() => {
					that.request({
						url: '/orderx/orderinfo1',
						data: {
							'danhao': danhao
						}, //充电线
						method: "POST"
					}).then(res => {
						console.log(res.data.data);
						if (res.data.data.status == 5) {
							console.log(res.data.data.status);
							console.log(that.orderOk);
							if (that.orderOk == 0) { //订单是否ok
								that.orderOk = 1;
								that.goodType = 2;
								// console.log("开始准备执行");
								// that.onLocationAuth();
								// that.goodType = 2;
								that.setSendStr();
								clearInterval(that.orderInterval);
								//模拟订单支付成功 启动充电线充电
								//地理位置检测
							}

						}
					});

				}, 300)

			},
			//支付订单
			orderPrice(item) {
				//开始支付订单ok
				//支付金额，时间
				// this.charger_number  设备id
				var that = this;
				that.positions = item.positions;
				let formData = {
					charger_number: that.charger_number,
					money: item.danjia,
					type: 2,
					userid: uni.getStorageSync('user_id'),
					qrcode: that.qrcode,
					goodscharger_id: item.id,
					goodscharger_name: item.name,
				};
				that.request({
					url: '/orderx/boxzorder',
					data: formData, //充电线
					method: "POST"
				}).then(res => {
					if (res.data.code == 200) {
						var danhao = res.data.data.orderinfo.danhao;
						that.danhao = danhao;
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							'timeStamp': res.data.data.payinfo.timeStamp,
							'nonceStr': res.data.data.payinfo.nonceStr,
							'package': res.data.data.payinfo.package,
							'signType': 'MD5',
							'paySign': res.data.data.payinfo.paySign,
							'success': function(res) {
								uni.showLoading({
									title: '正在查询',
								})
								that.orderInfo(danhao);
							},
							'fail': function(res) {
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								})
							}
						});
						// #endif
						
						// #ifdef MP-ALIPAY
						my.tradePay({
							tradeNO: res.data.data.payinfo.trade_no,
							success: (res1) => {
								if (res1.resultCode == 9000) {
									uni.showLoading({
										title: '正在查询',
									})
						
									that.orderInfo(danhao);
								} else {
									// 支付不成功，具体原因看返回，去对照文档
								}
							},
							fail: (err1) => {
								console.log(err1);
							}
						});
						// #endif

					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
					return false;
				});
			},



			onLocationAuth() {
				const _this = this // 下边this 为undefined
				console.log("金策蓝牙")
				// #ifdef MP-WEIXIN
				uni.authorize({
					scope: 'scope.userLocation', // 获取地理信息必填的参数，其它参数见文档
					success(res) {
						_this.getLocationFn()
					},
					// 授权失败
					fail(err) {
						err = err['errMsg']
						uni.showModal({
								title: '温馨提示',
								content: '为享受智能小程序，您必须授权!',
								showCancel: false,
								confirmText: '确认授权'
							})
							// 这里只设置了确认按钮，没有取消按钮
							.then(res => {
								//res ： [null, {cancel: false, confirm: true, errMsg: 'showModal: ok'}]
								if (res[1]['confirm']) { // 点击了确认按钮时
									// 调用下边方法时，会弹出 【使用我的地理位置】界面， 未设置直接返回，还是会走fail授权失败的函数，
									// 还是会弹出上边的温馨提示！！！
									// 如果设置, scope.userLocation: true
									uni.openSetting({
										success(res) {
											if(res.authSetting == 'scope.userLocation: true'){
												_this.getLocationFn()
											}
											// 如果不设置，res结果：
											// {errMsg: "openSetting:ok", authSetting: {scope.userLocation: false}}
											// 如果设置, res结果： 
											// {errMsg: "openSetting:ok", authSetting: {scope.userLocation: true}}
											console.log('小程序设置界面：', res)
										}
									})
								}
							})
					}
				})
				// #endif
				
				// #ifdef MP-ALIPAY
				_this.getLocationFn()
				// #endif
			},
			getLocationFn() {
				const _this = this;
				
				// #ifdef MP-WEIXIN
				uni.getLocation({
					type: 'gcj02', // <map> 组件默认为国测局坐标gcj02
					altitude: true,
					success(res) {
						console.log('返回的位置信息', res, _this)
						//初始化蓝牙
						_this.openBluetooth();
					}
				})
				// #endif
				
				// #ifdef MP-ALIPAY
				my.getLocation({
					type: 1, // 获取经纬度和省市区县数据
					success: (res) => {
						//初始化蓝牙
						_this.openBluetooth();
					},
					fail: (error) => {
						console.error('定位失败: ', JSON.stringify(error));
					},
					complete: () => {},
				});
				// #endif
			},

			openBluetooth() {
				var that = this;
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						// console.log(res)
						uni.showToast({
							title: '初始化成功',
							icon: 'success',
							duration: 800
						})
						that.findBlue(); //2.0
					},
					fail: function(res) { //如果手机上的蓝牙没有打开，可以提醒用户
						// uni.showToast({
						// 	title: '请打开蓝牙',
						// 	type: 'error',
						// 	icon: 'none'
						// });
						that.hidden = true;
					}
				})
			},

			//搜索附近蓝牙设备
			findBlue() {
				var that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success: function(res) {
						uni.showLoading({
							title: '正在搜索设备',
						})
						//搜索附近蓝牙设备
						that.getBlue() //3.0
					}
				})
			},
			/**
			 * 获取搜索到的蓝牙设备列表
			 */
			getBlue() {
				let that = this
				that.getBlueIntervalNum = 1
				that.getBluetoothIntval = setInterval(() => {
					that.getBlueIntervalNum++
					uni.getBluetoothDevices({
						success: function(res) {
							console.log("打印一下子开始");
							console.log(res);
							console.log("打印一下code码");
							// console.log(that.charger_number)
							let code_sn = that.charger_number
							console.log(code_sn);
							// if(that.data.bluetooth_name) code_sn = that.data.bluetooth_name
							console.log('搜索到的蓝牙设备列表=====IntervalNum=' + that.getBlueIntervalNum + '=======deviceId=' + that.deviceId + '====code_sn=' + code_sn, res)  
							that.bluetoothDevices = res.devices
							if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) { //查询8次还没有就终止
								clearInterval(that.getBluetoothIntval)
								that.getBluetoothIntval = null;
								uni.showToast({
									title: '未查找到设备',
									type: 'error',
									icon: 'none'
								});
								that.hidden = true;
								return false;
							}
							// console.log("打印一下完整的res");
							// console.log(res);
							if (res.devices.length > 0) {
								if (res.devices.length) {
									for (let i = 0; i < res.devices.length; i++) {
										console.log("查看一下搜索道德蓝牙设备")
										console.log(code_sn);
										console.log(res.devices[i]);
										console.log(res.devices[i].localName);
										console.log(code_sn === res.devices[i].localName);
										if ((code_sn === res.devices[i].localName || code_sn === res
												.devices[i].name)) {
											// console.log("执行这个了嗷")
											that.deviceId = res.devices[i].deviceId
											clearInterval(that.getBluetoothIntval)
											setTimeout(() => {
												console.log("执行到这里了吗");
												that.connectTO()
											}, 100)
											break
										}


										if ((code_sn === res.devices[i].localName || code_sn === res
												.devices[i].name) && !that.deviceId) {
											that.deviceId = res.devices[i].deviceId
											clearInterval(that.getBluetoothIntval)
											that.getBluetoothIntval = null;
											setTimeout(() => {
												that.connectTO()
											}, 100)
											break
										}
									}
								} else if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
									// that.postLog(1)
									clearInterval(that.getBluetoothIntval)
									that.getBluetoothIntval = null;
									that.hidden = true;
									uni.showToast({
										title: '未查找到设备',
										type: 'error',
										icon: 'none'
									});
								}
							} else if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
								clearInterval(that.getBluetoothIntval)
								that.getBluetoothIntval = null;
								that.hidden = true;
								uni.showToast({
									title: '未查找到设备',
									type: 'error',
									icon: 'none'
								});
							}
						},
						fail: function(err) {
							that.getBlueIntervalNum++
							// if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
							// 	clearInterval(that.getBluetoothIntval)
							// 	uni.showToast({
							// 		title: '未查找到设备',
							// 		type: 'error',
							// 		icon: 'none'
							// 	});
							// }
							console.log(err, '获取蓝牙设备列表失败=====' + that.getBlueIntervalNum)
						}
					})
				}, 2000)
			},



			/**
			 * 连接蓝牙
			 */
			connectTO() {
				let that = this
				uni.showLoading({
					title: '正在链接蓝牙',
				})
				that.connect_num = that.connect_num || 1
				that.connectedDeviceId = that.deviceId
				uni.createBLEConnection({
					deviceId: that.connectedDeviceId,
					success: function(res) {
						that.getBLEDeviceServices()
						uni.stopBluetoothDevicesDiscovery({
							success: function(res) {
								console.log(res, '链接蓝牙成功，停止搜索成功')
							},
							fail: function(res) {
								console.log(res, '链接蓝牙成功，停止搜索失败')
							}
						})
					},
					fail: function(err) {
						// that.postLog(2, err)
						if (err.errCode == -1 && err.errMsg.indexOf('already connect') > -1) {
							that.getBLEDeviceServices()
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log(res, '蓝牙已连接过，停止搜索成功')
								},
								fail: function(res) {
									console.log(res, '蓝牙已连接过，停止搜索失败')
								}
							})
						} else {
							that.connect_num++
							console.log(err, '链接蓝牙失败===' + that.connect_num)
							if (that.connect_num > 3 || !that.connect_num) {
								uni.showToast({
									title: '蓝牙连接失败',
									type: 'error',
									icon: 'none'
								});
							} else {
								setTimeout(() => {
									that.connectTO()
								}, 1000)
							}
						}
					}
				})
			},

			/**
			 * 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service
			 */
			getBLEDeviceServices() {
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: that.connectedDeviceId,
						success: function(res) {
							console.log(res, '获取蓝牙设备的service服务=========ok')
							that.services = res.services
							if (res.services.length > 0) {
								that.getBLEDeviceCharacteristics(0)
							} else {
								
								uni.showToast({
									title: '蓝牙服务获取失败',
									icon: 'none'
								})
							}
						},
						fail: function(err) {
							uni.showToast({
								title: '蓝牙服务获取失败',
								icon: 'none'
							})
							// uni.showModal({
							// 		title: '温馨提示',
							// 		content: '蓝牙服务获取失败',
							// 		showCancel: false,
							// 		confirmText: '确认'
							// 	})
							console.log(err, '获取蓝牙设备的service服务____err')
						}
					})
				}, 100)
			},

			/**
			 * 7.获取蓝牙设备特征值
			 * 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值id，
			 */
			getBLEDeviceCharacteristics(services_num) {
				let that = this
				that.notifyCharacteristicsId = ''
				that.writeCharacteristicsId = ''
				uni.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId: that.services[services_num].uuid,
					success: function(res) {
						console.log(res, '获取蓝牙设备特征值成功==========')
						that.characteristics = res.characteristics
						// for (var i = 0; i < res.characteristics.length; i++) {
						// 	let item = res.characteristics[i]

						// 	if ((item.properties.read && item.properties.write && item.properties.notify) || (
						// 			item.uuid.indexOf("FFF4") > -1)) {
						// 		/* 获取支持 notify 或者 indicate 的特征值 */
						// 		that.notifyCharacteristicsId = item.uuid
						// 		that.notifyServicweId = that.services[services_num].uuid
						// 	}
						// 	if ((item.properties.write) && !that.writeCharacteristicsId) {
						// 		that.writeCharacteristicsId = item.uuid
						// 		that.writeServicweId = that.services[services_num].uuid
						// 	}
						// 	if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
						// 		that.notifyBLECharacter()
						// 		break
						// 	}
						// }
						// if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
						// 	services_num = services_num + 1
						// 	if (services_num < that.services.length) {
						// 		that.getBLEDeviceCharacteristics(services_num)
						// 	} else {
						// 			uni.showToast({
						// 				title: '蓝牙特征值获取失败',
						// 				icon: 'none'
						// 			})
						// 	}
						// }
						// #ifdef MP-WEIXIN
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							console.log(item)
							if ((item.properties.read && item.properties.write && item.properties.notify) || (
									item.uuid.indexOf("FFF4") > -1)) {
									console.log(item.uuid.indexOf("FFF4"))	
								/* 获取支持 notify 或者 indicate 的特征值 */
								that.notifyCharacteristicsId = item.uuid
								that.notifyServicweId = that.services[services_num].uuid
							}
							if ((item.properties.write) && !that.writeCharacteristicsId) {
								that.writeCharacteristicsId = item.uuid
								that.writeServicweId = that.services[services_num].uuid
							}
							
							console.log(that.notifyCharacteristicsId + '11111' + that.writeCharacteristicsId)
							if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
								that.notifyBLECharacter()
								break
							}
						}
						if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
							services_num = services_num + 1
							if (services_num < that.services.length) {
								that.getBLEDeviceCharacteristics(services_num)
							} else {
								
								that.showModal('蓝牙特征值获取失败', 2)
							}
						}
						// #endif
						
						// #ifdef MP-ALIPAY
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							console.log(item)
							if ((item.properties.read && item.properties.write && item.properties.notify) || (
									item.characteristicId.indexOf("FFF4") > -1)) {
									console.log(item.characteristicId.indexOf("FFF4"))	
								/* 获取支持 notify 或者 indicate 的特征值 */
								that.notifyCharacteristicsId = item.characteristicId
								that.notifyServicweId = that.services[services_num].uuid
							}
							if ((item.properties.write) && !that.writeCharacteristicsId) {
								that.writeCharacteristicsId = item.characteristicId
								that.writeServicweId = that.services[services_num].uuid
							}
							
							console.log(that.notifyCharacteristicsId + '11111' + that.writeCharacteristicsId)
							if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
								that.notifyBLECharacter()
								break
							}
						}
						if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
							services_num = services_num + 1
							if (services_num < that.services.length) {
								that.getBLEDeviceCharacteristics(services_num)
							} else {
								
								that.showModal('蓝牙特征值获取失败', 2)
							}
						}
						// #endif
					},
					fail: function(err) {
						// that.showModal('蓝牙特征值获取失败', 2)
						uni.showToast({
							title: '蓝牙特征值获取失败',
							icon: 'none'
						})
						console.log(err, '获取蓝牙设备特征值====err')
					}
				})
			},
			/**
			 * 启用低功耗蓝牙设备特征值变化时的 notify 功能
			 * 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据
			 */
			notifyBLECharacter() {
				console.log("开始启用充电功能了？？？");
				uni.showLoading({
					title: '正在启用',
				})
				let that = this;
				let error = {
					10000: '未初始化蓝牙适配器',
					10001: '当前蓝牙适配器不可用',
					10002: '没有找到指定设备',
					10003: '连接失败',
					10004: '没有找到指定服务',
					10005: '没有找到指定特征值',
					10006: '当前连接已断开',
					10007: '当前特征值不支持此操作',
					10008: '其余所有系统上报的异常',
					10009: '系统版本低于4.3不支持蓝牙监听功能',
					10012: '连接超时',
					10013: '连接deviceId为空或者是格式不正确',
				};
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.connectedDeviceId,
					serviceId: that.notifyServicweId,
					characteristicId: that.notifyCharacteristicsId,
					complete(res) {
						console.log(res, '启用低功耗蓝牙设备监听=====complete')
						if (res.errCode >= 10000) {

							// that.showModal(error[res.errCode] || '很抱歉，设备通讯超时', 2)
							uni.showModal({
									title: '温馨提示',
									content: '很抱歉，设备通讯超时',
									showCancel: false,
									confirmText: '确认'
								})
						} else {
							// console.log("发送充电功能上")
							// console.log(pData);
							//判断一下设备

							console.log("发送充电功能");

							that.setSendStr()

						}
					}
				})
			},


			/**
			 * 监听手机蓝牙设备数据变化
			 */
			onBLECharacter() {
				let that = this;
				let type = that.type;
				var hexVal = '',
					endVal = ''

				uni.hideLoading();

				uni.onBLECharacteristicValueChange((res) => {
					// console.log(res, '监听手机蓝牙设备的数据变化===')
					// if(that.bluetooth_name) {
					//   hexVal = that.ab2hex(res.value)
					//   endVal = hexVal.substr(4, 2)
					// } else {
					// #ifdef MP-WEIXIN
					hexVal = '0x' + that.ab2hex(res.value)
					// #endif
					
					// #ifdef MP-ALIPAY
					hexVal = '0x' + res.value;
					// #endif
					hexVal = hexVal.toLowerCase()
					// console.log("打印一下返回整体数据开始");
					// console.log(hexVal);
					//查看一下返回的数据ok
					if (hexVal.substr(0, 4) == '0xf1') {
						endVal = hexVal.substr(6, 2)
					} else {
						//密码线是从第6位截取两位
						endVal = hexVal.substr(6, 2)


						// endVal = hexVal.substr(4, 2)
					}
					// }

					// console.log(hexVal)
					// console.log(endVal)
					// console.log("查看启动充电是否成功或者失败");

					if (hexVal.substr(4, 2) == '04') { //查看仓位信息
						// var formInfo = {
						// 'cang1'
						// }

						// console.log("仓位的信息");
						// console.log(that.deviceInfo1.good);
						//第8位截取两个 是第一个仓
						//获取货物状态
						//这个是仓位2
						if (hexVal.substr(6, 2) == '01') {
							//有货物就是01
							that.deviceInfo1.good[0].status = 1;

						} else {

							//没有货物就是00
							that.deviceInfo1.good[0].status = 2;

						}


						//这个是仓位1
						if (hexVal.substr(8, 2) == '01') {
							//有货物就是01
							that.deviceInfo1.good[1].status = 1;

						} else {
							//没有货物就是00
							that.deviceInfo1.good[1].status = 2;

						}

						// console.log("打印一下整体array");
						// console.log(that.deviceInfo1);

						var formData = {
							// 'id1':that.deviceInfo1.good[0].id,
							// 'id2':that.deviceInfo1.good[1].id,
							'id': that.charger_number,
							'goodst1': that.deviceInfo1.good[0].status,
							'goodst2': that.deviceInfo1.good[1].status,
							'positions1': that.deviceInfo1.good[0].positions,
							'positions2': that.deviceInfo1.good[1].positions,
						};

						// console.log("开始请求接口");
						// console.log(formData);
						//请求接口修改数据的状态
						that.request({
							url: '/wxdevice/boxzstup',
							data: formData,
							method: "POST"
						}).then(res => {
							console.log(res.data.data);
							
							//执行一下11111
							that.deviceInfoFun();
							// 	if (res.data.data.status == 5) {
							// 		console.log(res.data.data.status);
							// 		console.log(that.orderOk);
							// 		if (that.orderOk == 0) { //订单是否ok
							// 			that.orderOk = 1;
							// 			console.log("开始准备执行");
							// 			that.onLocationAuth();
							// 			clearInterval(that.orderInterval);
							// 			//模拟订单支付成功 启动充电线充电
							// 			//地理位置检测
							// 		}

							// 	}
						});

					} else if (hexVal.substr(4, 2) == '03') {

						if (endVal == '00' || endVal == '0000') {
							console.log('命令成功拉')

							that.sendProgress_status = true;
							var str = 'A6' + that.charger_pass;
							
							if(that.sucg==0){
								that.sucg = 1;
								uni.showModal({
									title: '温馨提示',
									content: `启动成功`,
									showCancel: false,
									confirmText: '确定',
									success() {
										console.log(that.sucg)
										// app.goBack()
										
										console.log(that.sucg)
										//请求后台接口查看一下商品详情
										that.deviceInfoFun();
										
									}
								})
							}
							
							
							// this.sendData(str);
							//      if(that.deviceReset){
							//        app.getPage(that.onPageNum).reloadCode().then(() => {
							//          app.getPage(that.onPageNum).getSendMsg().then(msg => {
							//            that.setSendStr(msg)
							//          })
							//        })
							//      }else{
							//        // 充电成功 或 结束成功
							//          that.sendProgress_status= true;
							// //跳转页面好了
							//      }
						} else {
							// 充电失败 或 结束失败
							// if(type == 3){
							// app.getPage(2).postEndOrder()
							// } else if(type == 4){
							uni.showModal({
								title: '温馨提示',
								content: `启动失败`,
								showCancel: false,
								confirmText: '确定',
								success() {
									// app.goBack()
								}
							})
							// } 
						}

						// uni.redirectTo({
						// 	url: '/pages/order/linedetail?danhao=' + that.danhao
						// })
					}




				})
			},


			/**
			 * 拼接发送的代码
			 * @param {*} msg 
			 */
			setSendStr(msg) {
				console.log("查看拼接的代码是什么啊");
				console.log(msg);
				this.sucg = 0;
				// this.getProgress('sendProgress');
				this.onBLECharacter();

				if (msg) {
					setTimeout(() => {
						this.sendData(msg)
					}, 50)
				} else {
					console.log("弹出命令开始");
					//查询一下设备的信息商品信息等
					//判断一下是什么命令哦
					if (this.goodType == 1) {
						//货物反馈信息
						// 12441
						// 24534
						var str = 'A6' + this.charger_pass;
						this.sendData(str);
					} else if (this.goodType == 2) {
						// 弹出的命令
						//判断一下是哪个
						var str = 'A' + this.positions + this.charger_pass;
						console.log("打印一下弹出命令");
						console.log(str);
						this.sendData(str);
					}
					// 			this.sendData(str)

				}
			},

			/**
			 * 向蓝牙设备发送数据
			 */
			sendData(str) {
				let that = this
				// 每哥字节前面都要0X  或者都不要
				// var token = "01 00430 2 05a4AEAA";
				//测试  之前二合一好使的
				// var token = "010043020005C151";
				var token = str;
				//密码二合一的
				//  var token = "F1010001000A"; //1分钟的
				// var token = "F10105A0000A"; //1440分钟的
				// var token = "050505050505";//结束订单的东西
				// console.log('sendStr=========', token)

				let buffer = new ArrayBuffer(token.length / 2)
				let dataView = new DataView(buffer)
				var buf = []
				for (var i = 0; i < token.length; i = i + 2) {
					buf.push(token.substr(i, 2))
				}

				for (var i = 0; i < buf.length; i++) {
					dataView.setUint8(i, "0x" + buf[i].toLowerCase());
				}


				// var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
				//   console.log("打印一下子");
				//   console.log(parseInt(h, 16));
				//   return parseInt(h, 16)
				// }))

				this.request({
					url: '/wxdevice/lineinfo',
					data: {
						qrcode: this.qrcode
					},
					method: "POST"
				}).then(res => {
					if (res.data.code == 200) {
						console.log(res.data.data)
						// this.arrpop = {};
						this.combo = res.data.data.combo;
						this.deviceInfo = res.data.data.device;
						this.charger_number = this.deviceInfo.charger_number;
						// console.log(this.charger_number);
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
				});



				that.sendNum = that.sendNum || 1
				console.log('发送message======' + that.sendNum)
				// console.log(typedArray.buffer)
				that.BLEValue = ''
				wx.writeBLECharacteristicValue({
					deviceId: that.connectedDeviceId,
					serviceId: that.writeServicweId,
					characteristicId: that.writeCharacteristicsId,
					value: buffer,
					success(res) {
						console.log("发送成功啦啦啦")
						console.log(res);
						console.log(res, 'message发送成功')
					},
					fail(res) {
						console.log('发送失败');
						console.log(res);
						if (that.sendNum > 3 || !that.sendNum) {
							// that.showModal('非常抱歉，发送信息失败', 2)
							uni.showModal({
									title: '温馨提示',
									content: '很抱歉，设备通讯超时',
									showCancel: false,
									confirmText: '确认'
								})
						} else {
							that.sendNum++
							that.sendData(str)
						}
						console.log(res, 'message发送失败')
					},
					complete(e) {
						that.onBLEFail = false
						console.log(e, 'message发送complete')
					}
				})
			},

			/**
			 * ArrayBuffer转16进制字符串示例
			 * @param {*} buffer 
			 */
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},

			/**
			 * modal提示
			 */
			showModal(title = '温馨提示', type = 1) {
				let that = this,
					text = '1、确保设备通电，2、重启手机蓝牙。3、确保手机定位开启。然后点击重新链接'
				if (type == 2) text = '确保设备通电，关闭小程序重新扫码。（如若还是无法链接成功，可尝试将设备断电10秒在给设备通电，而后在扫码。）'
				uni.showModal({
					title: title,
					content: text,
					showCancel: false,
					success() {
						if (type == 2) {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}
					}
				})
			},



			//打开蓝牙设备
			dakai() {
				uni.openSystemBluetoothSetting()
			},
			// 允许授权
			yunxu() {
				uni.openSetting()
			},
			fanhui() {
				uni.navigateBack()
			},
			topage(url) {
				uni.navigateTo({
					url
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.shop {
		width: 100%;
		margin: 0 auto;

		.head {
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 99;
			background: linear-gradient(90deg, #c5f9ff, #ddfcf8);

			.xztitle {
				position: fixed;
				left: 0%;
				top: 0;
				width: 100%;
				text-align: center;
				color: #333333;
				font-size: 32rpx;
			}

			.iconfont {
				position: absolute;
				top: 0;
				left: 14rpx;
				font-size: 44rpx;
			}
		}

		.headtop {
			width: 100%;

			image {
				width: 100%;
				height: 230rpx;
				display: flex;
			}
		}

		.content {
			width: 100%;
			margin-top: 20rpx;
			padding: 0 40rpx;
			box-sizing: border-box;

			.list {
				width: 48%;
				float: left;
				margin-right: 4%;
				background: #ffffff;
				border-radius: 16rpx;
				padding: 20rpx 20rpx;
				box-sizing: border-box;
				text-align: center;
				box-shadow: 0 0 7px rgba(0, 0, 0, 0.18);
				margin-bottom: 20rpx;
				position: relative;

				.image {
					width: 170rpx;
					height: 170rpx;
					margin: 0 auto;
				}

				.title {
					width: 100%;
					margin: 0 auto;
					text-align: left;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					text-overflow: ellipsis;
					-webkit-line-clamp: 2;
					overflow: hidden;
					font-weight: 700;
					font-size: 28rpx;
					color: #333333;
					margin-top: 30rpx;

					text {
						width: 72rpx;
						text-align: center;
						height: 32rpx;
						line-height: 32rpx;
						background: #46C7E2;
						border-radius: 20rpx;
						font-size: 24rpx;
						color: #FFFFFF;
						display: inline-block;
						margin-right: 8rpx;
					}
				}

				.li {
					margin-top: 20rpx;

					.price {
						color: #46C7E2;
						margin: 0 auto;
						text-align: left;
						font-weight: 700;
						font-size: 36rpx;
					}

					.goumai {
						color: #46C7E2;
						height: 40rpx;
						line-height: 40rpx;
						text-align: center;
						border-radius: 20rpx;
						width: 120rpx;
						border: 1rpx solid #46C7E2;
						font-size: 20rpx;
						margin-top: 4rpx;
					}

					.kaigui {
						color: #333333;
						height: 40rpx;
						line-height: 40rpx;
						text-align: center;
						border-radius: 20rpx;
						width: 120rpx;
						border: 1rpx solid #333333;
						font-size: 20rpx;
						margin-top: 4rpx;
					}

					.yishou {
						color: #999999;
						height: 40rpx;
						line-height: 40rpx;
						text-align: center;
						border-radius: 20rpx;
						width: 120rpx;
						border: 1rpx solid #999999;
						font-size: 20rpx;
						margin-top: 4rpx;
					}
				}

				.xuhao {
					position: absolute;
					top: 0;
					right: 0;
					width: 40rpx;
					height: 40rpx;
					line-height: 40rpx;
					text-align: center;
					background: #46C7E2;
					font-size: 24rpx;
					color: #FFFFFF;
					font-weight: 700;
					border-top-right-radius: 16rpx;
					border-bottom-left-radius: 16rpx;
				}
			}

			.list:nth-of-type(2n) {
				margin-right: 0;
			}
		}

		.kefu {
			position: fixed;
			width: 80rpx;
			text-align: center;
			bottom: 100rpx;
			right: 40rpx;

			image {
				width: 80rpx;
				height: 80rpx;
				display: flex;
			}

			.desc {
				font-size: 24rpx;
				color: #333333;
				margin-top: -6rpx;
			}
		}

		.beijing {
			position: fixed;
			width: 100%;
			top: 0;
			left: 0;
			height: 100vh;
			background: #000;
			opacity: 0.5;
		}

		.tankuang {
			position: fixed;
			width: 96%;
			top: 28%;
			left: 2%;

			.tankuangbj {
				width: 86%;
				height: 800rpx;
				position: absolute;
				top: 0;
				left: 7%;
			}

			.con {
				position: absolute;
				width: 80%;
				top: 0;
				left: 10%;
				text-align: center;

				.title {
					color: #333333;
					font-weight: 700;
					font-size: 32rpx;
					width: 100%;
					text-align: center;
					margin-top: 60rpx;
				}

				.detail {
					width: 90%;
					margin: 40rpx auto;
					text-align: left;

					.desc {
						color: #666666;
						margin-bottom: 30rpx;

						text {
							color: #447BF8;
						}
					}

					.yuxun {
						color: #427CF8;
						margin-bottom: 30rpx;
					}
				}

				.zhishi {
					width: 90%;
					margin: 80rpx auto 0;
					height: 120rpx;
				}
			}
		}
	}
</style>